package org.xlin.biz.util;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * 通用工具类
 * @author xl
 *
 */
public class UtilHandler {

	/**
	 * 获取编码后的文件名
	 * @param request
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static String handleFileNameByRequest(HttpServletRequest request, String fileName) throws IOException {
		if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
			return URLEncoder.encode(fileName, "utf-8");
		} else if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > -1) {
			return new String(fileName.getBytes("GB2312"), "ISO-8859-1");
		} else {
			return new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
		}
	}

	/**
	 * 处理 %|_
	 * @param param
	 * @return
	 */
	public static String handleSqlParam(String param) {
		// 去掉字符串两边的空字符串
		param = param.trim();
		// 处理之后的字符串
		StringBuffer sb = new StringBuffer();
		if (param != null) {
			// 处理'%' ,'_' 转换为'/%' ,'/_'
			Pattern p = Pattern.compile("%|_|/");
			Matcher matcher = p.matcher(param.trim());
			// 匹配个数标记
			int index = 0;
			while (matcher.find()) {
				matcher.appendReplacement(sb, "/" + matcher.group(index));
			}
			// 将最后一次匹配后剩余的字符串添加到sb中
			matcher.appendTail(sb);
		}
		return sb.toString();
	}

	/**
	 * 获取第N个字符在字符串中的索引位置
	 * @param str
	 * @param c
	 * @param count
	 * @return
	 */
	public static int getCharacterPosition(String str, String c, int count) {
		Matcher slashMatcher = Pattern.compile(c).matcher(str);
		int i = 0;
		while (slashMatcher.find()) {
			i++;
			if (i == count) {
				break;
			}
		}
		return slashMatcher.start();
	}
}
